package libs

import (
	"fmt"
	"godobase/common"
	"godobase/model"
	"godobase/pkg/db"

	"github.com/gin-gonic/gin"
	"github.com/samber/lo"
	"github.com/spf13/cast"
	"gorm.io/gorm"
)

// 根据等级获取部门领导人
func GetManagerListByeLevel(deptId int, level int) (userlist []model.User, err error) {
	userlist = make([]model.User, 0)

	//得到所有的部门数据
	var deptList []*model.UserDept
	db.DB.Select("id,pid").Find(&deptList)

	//得到当前部门数据
	nowDept, _ := lo.Find(deptList, func(item *model.UserDept) bool {
		return cast.ToInt(item.ID) == deptId
	})
	endFind := true
	for i := 2; i <= level; i++ {
		find := false
		for _, dept := range deptList {
			if dept.ID == nowDept.Pid {
				find = true
				nowDept = dept
				break
			}
		}
		//如果没有找到
		// if !find {
		// 	endFind = false
		// 	return
		// }
		if !find {
			return userlist, fmt.Errorf("unable to find parent department at level %d", i)
		}
	}

	if endFind {
		err = db.DB.Select("id,username,nickname").Where("dept_id=? and dept_auth='-1' and status=0", nowDept.ID).Find(&userlist).Error
	}
	return
}

// GetUserClaims 获取前台登录的用户信息
func GetUserClaims(c *gin.Context) (model.User, error) {
	userId := c.GetInt64("userId")
	if userId == 0 {
		return model.User{}, fmt.Errorf("user id not found")
	}

	// 缓存键
	key := "user:" + fmt.Sprintf("%d", userId)

	// 尝试从缓存中获取用户信息
	user, ok := common.GetCache(key)
	if ok == nil {
		// 转换缓存中的值为 model.User 类型
		userFromCache, ok := user.(model.User)
		if !ok {
			return model.User{}, fmt.Errorf("invalid cache data type")
		}
		return userFromCache, nil
	}

	// 如果缓存中没有，从数据库中查询
	var userData model.User
	if err := db.DB.Where("id = ?", userId).First(&userData).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return model.User{}, fmt.Errorf("user not found")
		}
		return model.User{}, err
	}
	userData.Password = ""
	// 更新缓存
	common.SetCache(key, userData, 10) // 设置缓存有效期为 10 分钟

	return userData, nil
}
